package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.TokenServess;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysSyncDepartService;

import org.jeecg.modules.system.vo.SysDepartSynVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysSyncDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysSyncDepartService {

    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 同步单位（实验室系统中的部门包含数智天研【单位、部门、岗位】）
     *
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    @Override
    public void syncCorpData() throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        TokenServess sztyServes = new TokenServess();
        String tokenServe = sztyServes.getTokenServe();
        String jsonString = sztyServes.getListAllCorp(null, tokenServe);

        // 创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();

        // 将字符串转换为JsonNode对象
        JsonNode jsonNode = mapper.readTree(jsonString);

        // 获取data属性的值
        JsonNode dataNode = jsonNode.get("data");
        if (dataNode.isArray()) {
            List<SysDepartSynVO> sysDepartList = new ArrayList<>();
            for (JsonNode unitNode : dataNode) {
                String unitCode = unitNode.get("code").asText();
                String unitName = unitNode.get("name").asText();
                String unitId = unitNode.get("id").asText();
                String unitReal = unitNode.get("real").asText();
                String unitType = unitNode.get("type").asText();
                String unitSeq = unitNode.get("seq").asText();

                SysDepartSynVO sysDepartVO = new SysDepartSynVO();
                sysDepartVO.setCode(unitCode);
                sysDepartVO.setName(unitName);
                sysDepartVO.setId(unitId);
                sysDepartVO.setReal(unitReal);
                sysDepartVO.setType(unitType);
                sysDepartVO.setSeq(unitSeq);

                sysDepartList.add(sysDepartVO);
            }
            syncUpdateOrSaveCorp(sysDepartList);
        }
    }

    /**
     * 根据传入数智天研的单位数据，更新单位数据
     *
     * @param synDepartList
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncUpdateOrSaveCorp(List<SysDepartSynVO> synDepartList) {

        //系统设置的顶层基础数据（天然气研究院、机关科室、基层单位）【org_category标识为1】
        QueryWrapper<SysDepart> initWraper = new QueryWrapper<>();
        initWraper.eq("org_category", "1");
        initWraper.eq("org_type", "1");
        List<SysDepart> initList = sysDepartService.list(initWraper);
        //数据库单位数据
        QueryWrapper<SysDepart> deparWraper = new QueryWrapper<>();
        deparWraper.eq("org_category", "2");
        deparWraper.eq("org_type", "1");
        List<SysDepart> departList = sysDepartService.list(deparWraper);
        //更新的单位数据
        List<SysDepart> modDepartList = new ArrayList<>();
        //新增的单位数据
        List<SysDepart> addDepartList = new ArrayList<>();
        //数据库中旧的单位数据
        List<SysDepart> oldDepartList = new ArrayList<>();

        //用同步的单位数据和当前数据库中的单位数据对比
        if (departList == null || departList.size() == 0) {
            for (SysDepartSynVO departVO : synDepartList) {
                String voId = departVO.getId();
                SysDepart sysDepart = new SysDepart();
                sysDepart.setDepartName(departVO.getName());
                sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                sysDepart.setOrgCategory("2");
//                sysDepart.setOrgType("1");
                sysDepart.setStatus("1");
                sysDepart.setDelFlag("0");
                sysDepart.setIzLeaf(0);
                sysDepart.setTCode(departVO.getCode());
                sysDepart.setTId(voId);
                sysDepart.setTReal(departVO.getReal());
                String type = departVO.getType();
                sysDepart.setTType(type);
                boolean bool = true;
                //如果同步过来的数据能找到上级单位，就把单位挂在对应的单位下
                for (SysDepart dep : initList) {
                    if (type.equals(dep.getTType())) {
                        sysDepart.setParentId(dep.getId());
                        bool = false;
                    }
                }
                //如果同步过来的数据不能找到上级单位，就把这个单位挂在“天然气研究院”下
                if (bool) {
                    for (SysDepart dep : initList) {
                        if ("0".equals(dep.getTType())) {
                            sysDepart.setParentId(dep.getId());
                        }
                    }
                }
                addDepartList.add(sysDepart);
            }
        } else {
            for (SysDepartSynVO departVO : synDepartList) {
                String voId = departVO.getId();
                boolean bool = true;
                for (SysDepart depart : departList) {
                    if (voId.equals(depart.getTId())) {
                        depart.setTCode(departVO.getCode());
                        depart.setDepartName(departVO.getName());
                        depart.setTId(voId);
                        depart.setTReal(departVO.getReal());
                        depart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                        String type = departVO.getType();
                        depart.setTType(departVO.getType());
                        for (SysDepart dep : initList) {
                            if (type.equals(dep.getTType())) {
                                depart.setParentId(dep.getId());
                            }
                        }
                        modDepartList.add(depart);
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    SysDepart sysDepart = new SysDepart();
                    sysDepart.setDepartName(departVO.getName());
                    sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                    sysDepart.setOrgCategory("2");
                    sysDepart.setOrgType("1");
                    sysDepart.setStatus("1");
                    sysDepart.setDelFlag("0");
                    sysDepart.setIzLeaf(0);
                    sysDepart.setTCode(departVO.getCode());
                    sysDepart.setTId(voId);
                    sysDepart.setTReal(departVO.getReal());
                    String type = departVO.getType();
                    sysDepart.setTType(type);
                    boolean bools = true;
                    //如果同步过来的数据能找到上级单位，就把单位挂在对应的单位下
                    for (SysDepart dep : initList) {
                        if (type.equals(dep.getTType())) {
                            sysDepart.setParentId(dep.getId());
                            bools = false;
                        }
                    }
                    //如果同步过来的数据不能找到上级单位，就把这个单位挂在“天然气研究院”下
                    if (bools) {
                        for (SysDepart dep : initList) {
                            if ("0".equals(dep.getTType())) {
                                sysDepart.setParentId(dep.getId());
                            }
                        }
                    }
                    addDepartList.add(sysDepart);
                }
            }
            //用当前数据库中的单位数据和同步的单位数据对比
            for (SysDepart depart : departList) {
                String voId = depart.getTId();
                boolean bool = true;
                for (SysDepartSynVO departVO : synDepartList) {
                    String tId = departVO.getId();
                    if (tId.equals(voId)) {
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    depart.setDelFlag("1");
                    depart.setStatus("0");//设置成不启用
                    oldDepartList.add(depart);
                }
            }
        }

        //更新单位数据
        sysDepartService.updateBatchById(modDepartList);
        //新增单位数据
        for (SysDepart depart : addDepartList) {
            JSONObject formData = new JSONObject();
            formData.put("parentId", depart.getParentId());
            String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART, formData);
            depart.setOrgCode(codeArray[0]);
            //系统返回的orgType标识
            //String orgType = codeArray[1];
            //人为设置固定的orgType标识
            depart.setOrgType("1");
            depart.setTOrgType("cor");
            sysDepartService.save(depart);
        }
        //更新旧的单位数据——设置成不启用
        sysDepartService.updateBatchById(oldDepartList);
    }

    /**
     * 同步部门数据 (org_category标识2；org_type标识2)
     *
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    @Override
    public void syncDepartData() throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        TokenServess sztyServes = new TokenServess();
        String tokenServe = sztyServes.getTokenServe();
        String jsonString = sztyServes.getListAllDepartment(null, null, tokenServe);

        // 创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();

        // 将字符串转换为JsonNode对象
        JsonNode jsonNode = mapper.readTree(jsonString);

        // 获取data属性的值
        JsonNode dataNode = jsonNode.get("data");
        if (dataNode.isArray()) {
            List<SysDepartSynVO> sysDepartList = new ArrayList<>();
            for (JsonNode unitNode : dataNode) {
                String unitCode = unitNode.get("code").asText();
                String unitCorpId = unitNode.get("corpId").asText();
                String unitName = unitNode.get("name").asText();
                String unitId = unitNode.get("id").asText();
                String unitReal = unitNode.get("real").asText();
                String unitType = unitNode.get("type").asText();
                String unitSeq = unitNode.get("seq").asText();

                SysDepartSynVO sysDepartVO = new SysDepartSynVO();
                sysDepartVO.setCode(unitCode);
                sysDepartVO.setCorpId(unitCorpId);
                sysDepartVO.setName(unitName);
                sysDepartVO.setId(unitId);
                sysDepartVO.setReal(unitReal);
                sysDepartVO.setType(unitType);
                sysDepartVO.setSeq(unitSeq);

                sysDepartList.add(sysDepartVO);
            }
            syncUpdateOrSaveDepart(sysDepartList);
        }
    }

    /**
     * 根据数智天研同步的部门数据更新实验室系统的部门数据
     *
     * @param synDepartList
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncUpdateOrSaveDepart(List<SysDepartSynVO> synDepartList) {

        //数据库单位数据
        QueryWrapper<SysDepart> compWraper = new QueryWrapper<>();
        compWraper.eq("org_category", "2");
        compWraper.eq("org_type", "1");
        List<SysDepart> comptList = sysDepartService.list(compWraper);

        //数据库部门数据
        QueryWrapper<SysDepart> deparWraper = new QueryWrapper<>();
        deparWraper.eq("org_category", "2");
        deparWraper.eq("org_type", "2");
        List<SysDepart> departList = sysDepartService.list(deparWraper);
        //更新的部门数据
        List<SysDepart> modDepartList = new ArrayList<>();
        //新增的部门数据
        List<SysDepart> addDepartList = new ArrayList<>();
        //数据库中旧的部门数据
        List<SysDepart> oldDepartList = new ArrayList<>();


        //用同步的部门数据和当前数据库中的部门数据对比
        if (departList == null || departList.size() == 0) {
            for (SysDepartSynVO departVO : synDepartList) {
                String voId = departVO.getId();
                SysDepart sysDepart = new SysDepart();
                sysDepart.setDepartName(departVO.getName());
                sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                sysDepart.setOrgCategory("2");
//                sysDepart.setOrgType("2");
                sysDepart.setStatus("1");
                sysDepart.setDelFlag("0");
                sysDepart.setIzLeaf(0);
                sysDepart.setTCode(departVO.getCode());
                sysDepart.setTId(voId);
                sysDepart.setTReal(departVO.getReal());
                String type = departVO.getType();
                sysDepart.setTType(type);
                String corpId = departVO.getCorpId();
                //如果同步过来的数据能找到上级单位，就把部门挂在对应的单位下
                for (SysDepart comp : comptList) {
                    if (corpId.equals(comp.getTId())) {
                        sysDepart.setParentId(comp.getId());
                    }
                }
                addDepartList.add(sysDepart);
            }
        } else {
            for (SysDepartSynVO departVO : synDepartList) {
                String voId = departVO.getId();
                boolean bool = true;
                for (SysDepart depart : departList) {
                    if (voId.equals(depart.getTId())) {
                        depart.setTCode(departVO.getCode());
                        depart.setDepartName(departVO.getName());
                        depart.setTId(voId);
                        depart.setTReal(departVO.getReal());
                        depart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                        depart.setTType(departVO.getType());
                        String corpId = departVO.getCorpId();
                        for (SysDepart comp : comptList) {
                            if (corpId.equals(comp.getTId())) {
                                depart.setParentId(comp.getId());
                            }
                        }
                        modDepartList.add(depart);
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    SysDepart sysDepart = new SysDepart();
                    sysDepart.setDepartName(departVO.getName());
                    sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                    sysDepart.setOrgCategory("2");
//                    sysDepart.setOrgType("2");
                    sysDepart.setStatus("1");
                    sysDepart.setDelFlag("0");
                    sysDepart.setIzLeaf(0);
                    sysDepart.setTCode(departVO.getCode());
                    sysDepart.setTId(voId);
                    sysDepart.setTReal(departVO.getReal());
                    String type = departVO.getType();
                    sysDepart.setTType(type);
                    String corpId = departVO.getCorpId();
                    //如果同步过来的数据能找到上级单位，就把部门挂在对应的单位下
                    for (SysDepart comp : comptList) {
                        if (corpId.equals(comp.getTId())) {
                            sysDepart.setParentId(comp.getId());
                        }
                    }
                    addDepartList.add(sysDepart);
                }
            }

            //用当前数据库中的单位数据和同步的单位数据对比
            for (SysDepart depart : departList) {
                String voId = depart.getTId();
                boolean bool = true;
                for (SysDepartSynVO departVO : synDepartList) {
                    String tId = departVO.getId();
                    if (tId.equals(voId)) {
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    depart.setDelFlag("1");
                    depart.setStatus("0");//设置成不启用
                    oldDepartList.add(depart);
                }
            }
        }

        //更新单位数据
        sysDepartService.updateBatchById(modDepartList);
        //新增单位数据
        for (SysDepart depart : addDepartList) {
            JSONObject formData = new JSONObject();
            formData.put("parentId", depart.getParentId());
            String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART, formData);
            depart.setOrgCode(codeArray[0]);
            //系统返回的orgType标识
            //String orgType = codeArray[1];
            //人为设置固定的orgType标识
            depart.setOrgType("2");
            depart.setTOrgType("dep");
            sysDepartService.save(depart);
        }
        //更新旧的单位数据——设置成不启用
        sysDepartService.updateBatchById(oldDepartList);


    }

    /**
     * 同步职务数据 (org_category标识3；org_type标识2)【实验室系统为岗位信息】
     *
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    @Override
    public void syncPositionData() throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        TokenServess sztyServes = new TokenServess();
        String tokenServe = sztyServes.getTokenServe();
        String jsonString = sztyServes.getListAllPosition(null, null, null, tokenServe);

        // 创建ObjectMapper对象
        ObjectMapper mapper = new ObjectMapper();

        // 将字符串转换为JsonNode对象
        JsonNode jsonNode = mapper.readTree(jsonString);

        // 获取data属性的值
        JsonNode dataNode = jsonNode.get("data");
        if (dataNode.isArray()) {
            List<SysDepartSynVO> sysDepartList = new ArrayList<>();
            for (JsonNode unitNode : dataNode) {
                String unitCorpId = unitNode.get("corpId").asText();
                String unitdepId = unitNode.get("departmentId").asText();
                String unitName = unitNode.get("name").asText();
                String unitId = unitNode.get("id").asText();

                SysDepartSynVO sysDepartVO = new SysDepartSynVO();
                sysDepartVO.setCorpId(unitCorpId);
                sysDepartVO.setDepId(unitdepId);
                sysDepartVO.setName(unitName);
                sysDepartVO.setId(unitId);

                sysDepartList.add(sysDepartVO);
            }
            syncUpdateOrSavePosition(sysDepartList);
        }
    }

    /**
     * 根据数智天研同步的职务数据更新实验室系统的岗位数据
     *
     * @param synPositList
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncUpdateOrSavePosition(List<SysDepartSynVO> synPositList) {
        //数据库单位数据
        QueryWrapper<SysDepart> compWraper = new QueryWrapper<>();
        compWraper.eq("org_category", "2");
        compWraper.eq("org_type", "1");
        List<SysDepart> comptList = sysDepartService.list(compWraper);

        //数据库部门数据
        QueryWrapper<SysDepart> departWraper = new QueryWrapper<>();
        departWraper.eq("org_category", "2");
        departWraper.eq("org_type", "2");
        List<SysDepart> departList = sysDepartService.list(departWraper);

        //数据库部门数据
        QueryWrapper<SysDepart> postWraper = new QueryWrapper<>();
        postWraper.eq("org_category", "3");
        postWraper.eq("org_type", "2");
        List<SysDepart> positionList = sysDepartService.list(postWraper);

        //更新的部门数据
        List<SysDepart> modDepartList = new ArrayList<>();
        //新增的部门数据
        List<SysDepart> addDepartList = new ArrayList<>();
        //数据库中旧的部门数据
        List<SysDepart> oldDepartList = new ArrayList<>();

        //用同步的职务数据和当前数据库中的岗位数据对比
        if (positionList == null || positionList.size() == 0) {
            for (SysDepartSynVO departVO : synPositList) {
                String voId = departVO.getId();
                String corpId = departVO.getCorpId();
                String depId = departVO.getDepId();
                SysDepart sysDepart = new SysDepart();
                sysDepart.setDepartName(departVO.getName());
                sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                sysDepart.setOrgCategory("3");
                sysDepart.setStatus("1");
                sysDepart.setDelFlag("0");
                sysDepart.setIzLeaf(1);
                sysDepart.setTId(voId);
                //如果同步过来的职务数据能找到上级部门/单位，就把部门挂在对应的部门/单位下
                if (depId != null && !"".equals(depId) && !"null".equals(depId)) {
                    for (SysDepart dep : departList) {
                        if (depId.equals(dep.getTId())) {
                            sysDepart.setParentId(dep.getId());
                        }
                    }
                } else {
                    for (SysDepart comp : comptList) {
                        if (corpId != null && corpId.equals(comp.getTId())) {
                            sysDepart.setParentId(comp.getId());
                        }
                    }
                }
                addDepartList.add(sysDepart);
            }
        } else {
            for (SysDepartSynVO departVO : synPositList) {
                String voId = departVO.getId();
                boolean bool = true;
                for (SysDepart depart : positionList) {
                    if (voId.equals(depart.getTId())) {
                        depart.setTCode(departVO.getCode());
                        depart.setDepartName(departVO.getName());
                        depart.setTId(voId);
                        depart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                        String depId = departVO.getDepId();
                        String corpId = departVO.getCorpId();
                        //如果同步过来的职务数据能找到上级部门/单位，就把部门挂在对应的部门/单位下
                        if (depId != null && !"".equals(depId) && !"null".equals(depId)) {
                            for (SysDepart dep : departList) {
                                if (depId.equals(dep.getTId())) {
                                    depart.setParentId(dep.getId());
                                }
                            }
                        } else {
                            for (SysDepart comp : comptList) {
                                if (corpId.equals(comp.getTId())) {
                                    depart.setParentId(comp.getId());
                                }
                            }
                        }
                        modDepartList.add(depart);
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    SysDepart sysDepart = new SysDepart();
                    sysDepart.setDepartName(departVO.getName());
                    sysDepart.setDepartOrder(Integer.getInteger(departVO.getSeq()));
                    sysDepart.setOrgCategory("3");
                    sysDepart.setStatus("1");
                    sysDepart.setDelFlag("0");
                    sysDepart.setIzLeaf(1);
                    sysDepart.setTId(voId);
                    String depId = departVO.getDepId();
                    String corpId = departVO.getCorpId();
                    //如果同步过来的职务数据能找到上级部门/单位，就把部门挂在对应的部门/单位下
                    if (depId != null && !"".equals(depId) && !"null".equals(depId)) {
                        for (SysDepart dep : departList) {
                            if (depId.equals(dep.getTId())) {
                                sysDepart.setParentId(dep.getId());
                            }
                        }
                    } else {
                        for (SysDepart comp : comptList) {
                            if (corpId.equals(comp.getTId())) {
                                sysDepart.setParentId(comp.getId());
                            }
                        }
                    }
                    addDepartList.add(sysDepart);
                }
            }

            //用当前数据库中的单位数据和同步的单位数据对比
            for (SysDepart depart : positionList) {
                String voId = depart.getTId();
                boolean bool = true;
                for (SysDepartSynVO departVO : synPositList) {
                    String tId = departVO.getId();
                    if (tId.equals(voId)) {
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    depart.setDelFlag("1");
                    depart.setStatus("0");//设置成不启用
                    oldDepartList.add(depart);
                }
            }
        }

        //更新岗位数据
        sysDepartService.updateBatchById(modDepartList);
        //新增岗位数据
        for (SysDepart depart : addDepartList) {
            JSONObject formData = new JSONObject();
            String parentId = depart.getParentId();
            formData.put("parentId", parentId);
            String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART, formData);
            depart.setOrgCode(codeArray[0]);
            //系统返回的orgType标识
            //String orgType = codeArray[1];
            //人为设置固定的orgType标识
            depart.setOrgType("2");
            depart.setTOrgType("pos");
            if (parentId == null || parentId == "") {
                depart.setDelFlag("1");
                depart.setStatus("0");
            }
            sysDepartService.save(depart);
        }
        //更新旧的岗位数据——设置成不启用
        sysDepartService.updateBatchById(oldDepartList);

    }

    @Transactional(rollbackFor = Exception.class)
    public void syncUpdateDepart() {

    }


}
